package cn.school.demo.repository

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import cn.school.demo.pojo.Result
import cn.school.demo.util.HttpApi
import com.blankj.utilcode.util.LogUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class ForgetPasswordRepository {
    private val httpApi: HttpApi

    init {
        val retrofit =
            Retrofit.Builder().baseUrl(DataRepository.BASEURL).addConverterFactory(
                GsonConverterFactory.create()
            )
                .build()
        httpApi = retrofit.create(HttpApi::class.java)
    }

    //用户验证
    fun userDetection(id: String, phone: String): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        val params = mapOf("sfNumber" to id.toInt(), "telephoneNumber" to phone)
        httpApi.userDetection(params).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                LogUtils.d("忘记密码身份验证http回调成功！")
                response.body()?.let { responseLiveData.value = response.body() } ?: let {
                    LogUtils.e("忘记密码身份验证http返回值为空！")
                }
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }

    //重置密码
    fun resetPassword(map: Map<String, Any>): LiveData<Result> {
        val responseLiveData = MutableLiveData<Result>()
        httpApi.resetPassword(map).enqueue(object : Callback<Result> {
            override fun onResponse(call: Call<Result>, response: Response<Result>) {
                LogUtils.d("忘记密码重置密码http回调成功！")
                response.body()?.let { responseLiveData.value = response.body() } ?: let {
                    LogUtils.e("忘记密码重置密码http返回值为空！")
                }
            }

            override fun onFailure(call: Call<Result>, t: Throwable) {
                LogUtils.e(t)
            }
        })
        return responseLiveData
    }
}